package com.qiuyang.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiuyang.pojo.Type;
import com.qiuyang.service.TypeService;
import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;
    /*-------------------------------------------------------------------------------------*/

    //查询分页
    @RequestMapping("/type")
    public String getAllType(Model model,@RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum){
        PageHelper.startPage(pageNum,5);
        List<Type> allType = typeService.getAllType();
        PageInfo<Type> typePageInfo = new PageInfo<>(allType);
        model.addAttribute("pageInfo",typePageInfo);
        return "admin/types";
    }

    //去添加
    @RequestMapping("/toInputType")
    public String input(Model model){
        model.addAttribute("type",new Type());
        return "admin/types-input";
    }

    @PostMapping("/inputType")
    @ResponseBody
    public String insertType(Type type){
        //将name中的所有空格相关的东西去掉
        String s = type.getName().replaceAll("\\s*", "");
        Type type1 = typeService.findTypeByName(type.getName());
        if (type1!=null){
            return "已存在该名称！";
        }
        if (s.length()==0){
            return "请输入正确的名称！";
        }
        typeService.insertType(type);
        return "添加成功";
    }
    //删除
    @GetMapping("/types/delete/{id}")
    public String delete(@PathVariable Long id){
        typeService.deleteTypes(id);
        return "redirect:/admin/type";
    }

    //去修改
    @GetMapping("/types/update/{id}")
    public String update(@PathVariable Long id, Model model){
        model.addAttribute("type",typeService.findTypeById(id));
        return "admin/types-input";
    }

    //修改
    @PostMapping("/updatetype")
    @ResponseBody
    public String updateType(Type type) throws NotFoundException {
        Type typeByName = typeService.findTypeByName(type.getName());
        String s = type.getName().replaceAll("\\s*", "");
        if (typeByName!=null){
            return "名称已存在，请重新输入！";
        }
        if (s.length()==0){
            return "请输入正确的名称！";
        }
        typeService.updateTypes(type);
        return "修改成功";
    }


}
